<?php

namespace App\Console\Commands\Tools\DbExport\Order;

use App\Kuafu\Order\Service\OrderDb;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use League\Csv\CannotInsertRecord;
use League\Csv\Writer;

/**
 * 数据导出
 */
class OrderAllDbExportCommand extends Command
{
    protected $signature   = 'tools:order-all-db-export';
    protected $description = '';

    /**
     * @throws \Exception
     */
    public function handle()
    {
        ini_set('memory_limit', '2G');

        $shopId = '12789';

        $exportList = [
            'order',
            'order_detail',
            'pay_stream',
            'waimai_orders',

//            'order_coupon',
//            'order_coupon_external',
//            'order_discount',
//            'order_external',
//            'order_pay_union',
//
//            'waimai_order_details',
        ];
        foreach ($exportList as $tableName) {
            $this->doHandle($tableName, $shopId);
        }

    }

    /**
     * @throws CannotInsertRecord
     * @throws \Exception
     */
    private function doHandle($tableName, $shopId): void
    {
        $tmpList = explode('_', $tableName);

        if (!is_numeric(end($tmpList))) {
            $tableName = self::orderDetailTableName($tableName, $shopId);
        }

        $primaryKey = self::getPrimaryId($tableName);

        $path     = storage_path() . '/logs/backupOrderDb/';
        $fileName = $tableName . '_' . date('YmdH') . '.csv';

        $csv = Writer::createFromPath($path . $fileName, 'w+');

        $orderDbConnection = OrderAllDbExportCommand::getOrderDbConnection($tableName, $shopId);
        // 设置列标题
        $columns = Schema::connection($orderDbConnection)->getColumnListing($tableName);
        sort($columns);

        $csv->insertOne($columns);

        // 拉对应时间的数据 - $day 天
        DB::connection($orderDbConnection)
          ->table($tableName)
          ->where('shopId', $shopId)
          ->orderBy($primaryKey)
          ->when(in_array('isDeleted', $columns), function ($query) {
              return $query->where('isDeleted', 0);
          })
//          ->where('createdAt', '<=', strtotime('2023-12-01'))
//          ->where('createdAt', '>=', strtotime('2023-11-01'))
          ->chunkById(1000,
                function ($lines) use ($csv) {
                    foreach ($lines as $line) {
                        $line     = json_encode($line);
                        $lineData = json_decode($line, true);
                        ksort($lineData);
                        $csv->insertOne($lineData);
                    }
                }, $primaryKey);

        $this->info('Exported ' . $tableName . ' successfully!');
    }

    /**
     * 获取 订单详情分表表名
     *
     * @param $tableName
     * @param int $shopId
     * @return string
     */
    public static function orderDetailTableName($tableName, $shopId): string
    {
        return $tableName . '_' . str_pad((int)$shopId % 100, 3, 0, 0);
    }

    public static function getPrimaryId($tableName): string
    {
        $primaryKey = 'id';

        if (strpos($tableName, 'pay_stream') !== false) {
            $primaryKey = 'payNo';
        }

        $tmpList = explode('_', $tableName);
        unset($tmpList[count($tmpList) - 1]);

        $tmpTName = implode('_', $tmpList);

        if ($tmpTName == 'order') {
            $primaryKey = 'orderId';
        }

        if ($tmpTName == 'waimai_orders') {
            $primaryKey = 'orderId';
        }

        return $primaryKey;
    }

    public static function getOrderDbConnection($tableName, $shopId): string
    {
        if (strpos($tableName, 'waimai') !== false) {
            $dbType = OrderDb::DB_TYPE_WAIMAI;
        } else {
            $dbType = OrderDb::DB_TYPE_ORDER;
        }

        return OrderDb::orderDbConnection($shopId, $dbType);
    }

}
